package com.llt.mp.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.llt.mp.domain.dto.PageDto;
import com.llt.mp.domain.po.Address;
import com.llt.mp.domain.po.User;
import com.llt.mp.domain.query.UserQuery;
import com.llt.mp.domain.vo.AddressVO;
import com.llt.mp.domain.vo.UserVO;
import com.llt.mp.enums.UserStatus;
import com.llt.mp.mapper.UserMapper;
import com.llt.mp.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceimpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public void deductMoneyById(Long id, Integer money) {
        // 1. 查询用户
        User user = getById(id);
        // 2. 校验用户状态
        if(user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常");
        }
        // 3. 校验余额
        if (user.getBalance() < money) {
            throw new RuntimeException("余额不足");
        }
        // 4. 扣减余额
        int re = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, re)
                .set(re == 0,User::getBalance, UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁
                .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        // gt - 大于， lt - 小于
        return  lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .gt(minBalance != null, User::getBalance, minBalance)
                .lt(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public List<UserVO> queryUserByIds2(List<Long> ids) {

        // 1. 查询用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return null;
        }

        // 2. 查询地址
        // 根据 id 查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, ids).list();
        // 转换地址vo
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        // 整理地址，使同一个用户的地址对应上
        Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)) {
            addressMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }

        // 3. 转 vo
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
            // 转换 user 的 po 为 vo
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);
            list.add(vo);
            // 将地址也填上
            vo.setAddress(addressMap.get(user.getId()));
        }

        return list;
    }

    @Override
    public PageDto<UserVO> queryUserPages(UserQuery query) {
        String name = query.getName();
        log.info("name: " + name);
        Integer status = query.getStatus();
        // 1. 构建分页条件和排序条件
        Page<User> page = query.toMpPage();

        // 2. 分页查询
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

        // 3. 封装 VO 结果
        // 4. 返回
        return PageDto.of(p, UserVO.class);
    }
}
